package com.sxrong.carloan.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.sxrong.carloan.BuildConfig;
import com.sxrong.carloan.R;
import com.sxrong.carloan.dto.BaseBean;
import com.sxrong.carloan.dto.CarInfoBean;
import com.sxrong.carloan.dto.CarPhotoBean;
import com.sxrong.carloan.dto.QiNiuBean;
import com.sxrong.carloan.net.ApiService;
import com.sxrong.carloan.net.MyCallBack;
import com.sxrong.carloan.net.XUtils;
import com.sxrong.carloan.utils.AppCacheSharedPreferences;
import com.sxrong.carloan.utils.Config;
import com.sxrong.carloan.utils.ImageUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CarInfoActivity extends Activity implements View.OnClickListener {
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private static final int TAKE_CPH_CARMRE_CODE = 12;
    private static final int TAKE_CJH_CARMRE_CODE = 11;


    private static final int PROGRESS_CODE = 13;
    private static final int PROGRESS_COMPLETE_CODE = 14;
    private static final int PROGRESS_VIN_CODE = 15;
    private static final int PROGRESS_VIN_COMPLETE_CODE = 16;
    private RxPermissions permissions;
    private PhotoView carImageImageView, carImageImageView2;
    private Uri imageUri;
    private TextView progress_tv, progress_tv1;

    private Bitmap cphDraweBitmap;
    private Bitmap cphYuanBitmap;
    private Bitmap cjhDraweBitmap;
    private Bitmap cjhYuanBitmap;

    private String locationStr; // 位置信息

    private String cphPhotoUrl;
    private String cjhPhotoUrl;


    private Button goto_carma;
    private Button goto_carma2;

    private TextView edit;    //编辑
    private EditText jkr, cz, jkrq, gs, cx, cph, ys, jkze, momo, cjh;

    private boolean is_edit = false;

    private boolean is_cph_upload_image = false;
    private boolean is_cjh_upload_image = false;

    public boolean is_submit = false ;

    private CarInfoBean bean;


    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PROGRESS_CODE:
                    is_cph_upload_image = true;
                    progress_tv.setVisibility(View.VISIBLE);
                    progress_tv.setText("当前进度" + msg.arg1 + "%");
                    carImageImageView.setEnabled(false);
                    break;
                case PROGRESS_COMPLETE_CODE:
                    is_cph_upload_image = false;
                    progress_tv.setVisibility(View.VISIBLE);
                    carImageImageView.setEnabled(true);
                    break;
                case PROGRESS_VIN_CODE:
                    is_cjh_upload_image = true;
                    progress_tv1.setVisibility(View.VISIBLE);
                    progress_tv1.setText("当前进度" + msg.arg1 + "%");
                    break;
                case PROGRESS_VIN_COMPLETE_CODE:
                    is_cjh_upload_image = false;
                    progress_tv1.setVisibility(View.VISIBLE);
                    carImageImageView.setEnabled(true);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_info);
        permissions = new RxPermissions(CarInfoActivity.this);
        initLocation();
        carImageImageView = findViewById(R.id.car_image_iv);
        carImageImageView2 = findViewById(R.id.car_vin_photo);
        progress_tv = findViewById(R.id.progress_tv);
        progress_tv1 = findViewById(R.id.car_vin_progress_tv);
        jkr = findViewById(R.id.jkr);
        cz = findViewById(R.id.cz);
        jkrq = findViewById(R.id.jkrq);
        gs = findViewById(R.id.gs);
        cx = findViewById(R.id.cx);
        cph = findViewById(R.id.cph);
        ys = findViewById(R.id.ys);
        jkze = findViewById(R.id.jkze);
        edit = findViewById(R.id.edit);
        momo = findViewById(R.id.momo_tv);
        cjh = findViewById(R.id.cjh);
        goto_carma = findViewById(R.id.goto_carma);
        goto_carma2 = findViewById(R.id.goto_carma2);

        bean = (CarInfoBean) getIntent().getSerializableExtra("data");
        if (bean == null) {
            is_edit = false;
        } else {
            is_edit = true;
            bindDate();
        }

        if (!is_edit) {
            setCanEdit(true);
            is_edit = true;
            edit.setText("保存");
        } else {
            setCanEdit(false);
            is_edit = false;
            edit.setText("编辑");
        }
        carImageImageView.setOnClickListener(this);
        carImageImageView2.setOnClickListener(this);
        edit.setOnClickListener(this);
        goto_carma.setOnClickListener(this);
        goto_carma2.setOnClickListener(this);

    }

    //jkr, cz, jkrq, gs, cx, cph, ys, jkze;
    private void bindDate() {
        jkr.setText(bean.getBorrower());
        cz.setText(bean.getCarman());
        jkrq.setText(bean.getDate());
        gs.setText(bean.getCompany());
        cx.setText(bean.getCarModel());
        cph.setText(bean.getCarNo());
        ys.setText(bean.getColor());
        jkze.setText(bean.getBorroweAmount());
        momo.setText(bean.getMemo());
        cjh.setText(bean.getVinno());
        getCarPhotoDate();
    }

    private void initLocation() {
        permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    mLocationClient = new LocationClient(getApplicationContext());
                    //声明LocationClient类
                    mLocationClient.registerLocationListener(myListener);
                    LocationClientOption option = new LocationClientOption();
                    option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                    option.setCoorType("bd09ll");
                    option.setScanSpan(1000);
                    option.setOpenGps(true);
                    option.setLocationNotify(true);
                    option.setIgnoreKillProcess(false);
                    option.SetIgnoreCacheException(false);
                    option.setWifiCacheTimeOut(5 * 60 * 1000);
                    option.setEnableSimulateGps(false);
                    option.setIsNeedAddress(true);
                    mLocationClient.setLocOption(option);
                    mLocationClient.start();
                } else {
                    Toast.makeText(CarInfoActivity.this, "请打开定位权限", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_CPH_CARMRE_CODE && resultCode == RESULT_OK) {
          /*  Uri date = data.getDataString();
            Toast.makeText(this, date, Toast.LENGTH_SHORT).show();*/
            Glide.with(this).load(imageUri).asBitmap().diskCacheStrategy(DiskCacheStrategy.NONE).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    if (cphDraweBitmap != null && !cphDraweBitmap.isRecycled()) {
                        cphDraweBitmap.recycle();
                    }
                    if (cphYuanBitmap != null && cphYuanBitmap.isRecycled()) {
                        cphYuanBitmap.recycle();
                    }
                    cphYuanBitmap = ImageUtils.martixBitmap(resource);
                    getQiNiuToken(TAKE_CPH_CARMRE_CODE);
                }
            });
        }

        if (requestCode == TAKE_CJH_CARMRE_CODE && resultCode == RESULT_OK) {
            Glide.with(this).load(imageUri).asBitmap().diskCacheStrategy(DiskCacheStrategy.NONE).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    if (cjhDraweBitmap != null && !cjhDraweBitmap.isRecycled()) {
                        cjhDraweBitmap.recycle();
                    }
                    if (cjhYuanBitmap != null && cjhYuanBitmap.isRecycled()) {
                        cjhYuanBitmap.recycle();
                    }
                    cjhYuanBitmap = ImageUtils.martixBitmap(resource);
                    getQiNiuToken(TAKE_CJH_CARMRE_CODE);
                }
            });
        }
    }

    public void getCarPhotoDate() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("car", bean.getId() + "");
        XUtils.Get(ApiService.GET_CAR_PHOTO_URL, hashMap, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                if (isFinishing()) {
                    return;
                }

                CarPhotoBean carPhotoBean = new Gson().fromJson(result, CarPhotoBean.class);
                for (CarPhotoBean.DataBean bean1 : carPhotoBean.getData()) {
                    if (bean1.getPhotoType() == 0) {
                        cphPhotoUrl = bean1.getUrl();
                        Glide.with(CarInfoActivity.this).load(bean1.getUrl()).into(carImageImageView);
                    } else {
                        cjhPhotoUrl = bean1.getUrl();
                        Glide.with(CarInfoActivity.this).load(bean1.getUrl()).into(carImageImageView2);
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                if (isFinishing()) {
                    return;
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.goto_carma:
                gotoCamera(TAKE_CPH_CARMRE_CODE);
                break;
            case R.id.goto_carma2:
                gotoCamera(TAKE_CJH_CARMRE_CODE);
                break;
            case R.id.edit:
                isEdit();
                break;
            case R.id.car_image_iv :
                gotoPhotoActivity(0);
                break;
            case R.id.car_vin_photo:
                gotoPhotoActivity(1);
                break;
        }
    }

    public void gotoPhotoActivity(int index){
        ArrayList<String> list = new ArrayList<>();
        if (TextUtils.isEmpty(cphPhotoUrl)) {
            Toast.makeText(CarInfoActivity.this, "请先上传车牌照图片", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(cjhPhotoUrl)){
            Toast.makeText(CarInfoActivity.this, "请先上传车架照图片", Toast.LENGTH_SHORT).show();
            return;
        }
        list.add(cphPhotoUrl);
        list.add(cjhPhotoUrl);
        Intent intent = new Intent(CarInfoActivity.this, PhotoActivity.class);
        intent.putStringArrayListExtra("imgs", list);
        intent.putExtra("index", index);
        startActivity(intent);
    }

    private void gotoCamera(final int code) {
        if (!is_edit) {
            Toast.makeText(this, "要想更换图片,请点击编辑按钮进行编辑", Toast.LENGTH_SHORT).show();
            return;
        }
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
                        Toast.makeText(CarInfoActivity.this, "抱歉,您的设备上没有摄像头", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent imageCaptureIntent = new Intent(
                            MediaStore.ACTION_IMAGE_CAPTURE);
                    imageUri = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
                            FileProvider.getUriForFile(CarInfoActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", new File(Environment.getExternalStorageDirectory(), "image.jpg"))
                            : Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
                    imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    if (imageCaptureIntent.resolveActivity(getPackageManager()) == null) {
                        Toast.makeText(CarInfoActivity.this, "抱歉,您的设备上没有摄像头", Toast.LENGTH_SHORT).show();
                    } else {
                        startActivityForResult(imageCaptureIntent,
                                code);
                    }
                } else {
                    Toast.makeText(CarInfoActivity.this, "申请权限失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private void isEdit() {
        if (!is_edit) {
            setCanEdit(true);
            is_edit = true;
            edit.setText("保存");
        } else {
            if (TextUtils.isEmpty(jkr.getText().toString().trim()) || TextUtils.isEmpty(cz.getText().toString().trim()) ||
                    TextUtils.isEmpty(jkrq.getText().toString().trim()) || TextUtils.isEmpty(gs.getText().toString().trim())
                    || TextUtils.isEmpty(cph.getText().toString()) || TextUtils.isEmpty(cx.getText().toString()) || TextUtils.isEmpty(ys.getText().toString().trim())
                    || TextUtils.isEmpty(jkze.getText().toString().trim()) || TextUtils.isEmpty(momo.getText().toString().trim()) || TextUtils.isEmpty(cjh.getText().toString().trim())) {
                Toast.makeText(CarInfoActivity.this, "请完善所有信息后保存", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!isValidDate(jkrq.getText().toString().trim())) {
                Toast.makeText(CarInfoActivity.this, "请填写正确的借款日期", Toast.LENGTH_SHORT).show();
                return;
            }

            if (is_cph_upload_image) {
                Toast.makeText(CarInfoActivity.this, "车牌号的图片正在上传,请耐心等待", Toast.LENGTH_SHORT).show();
                return;
            }

            if(is_cjh_upload_image){
                Toast.makeText(CarInfoActivity.this, "车架号的图片正在上传,请耐心等待", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(cphPhotoUrl)) {
                Toast.makeText(CarInfoActivity.this, "亲, 您忘记上传车牌号的图片了 ^-^ ,点击下方的按钮即可拍照上传哦", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(cjhPhotoUrl)) {
                Toast.makeText(CarInfoActivity.this, "亲, 您忘记上传车架号的图片了 ^-^ ,点击下方的按钮即可拍照上传哦", Toast.LENGTH_SHORT).show();
                return;
            }

            if(is_submit){
                Toast.makeText(this, "您正在提交资料,请稍后片刻", Toast.LENGTH_SHORT).show();
                return;
            }
            is_submit = true;

            setCanEdit(false);
            is_edit = false;
            edit.setText("编辑");
            addCarInfo(jkr.getText().toString().trim(), cz.getText().toString().trim(), jkrq.getText().toString().trim(), gs.getText().toString().trim(), cph.getText().toString(), cx.getText().toString().trim(), ys.getText().toString().trim(), jkze.getText().toString().trim(), momo.getText().toString().trim() , cjh.getText().toString());
        }
    }

    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            locationStr = location.getCity() + location.getDistrict() + location.getStreet();
        }
    }

    public void getQiNiuToken(final int code) {
        XUtils.Get(ApiService.QINIU_URL, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                QiNiuBean bean = new Gson().fromJson(result, QiNiuBean.class);
                if (bean.getCode() == 1) {
                    if (code == TAKE_CPH_CARMRE_CODE) {
                        cphDraweBitmap =ImageUtils.drawTextToRightBottom(CarInfoActivity.this, cphYuanBitmap, bean.getData().getDate(), locationStr, 32, ContextCompat.getColor(CarInfoActivity.this, R.color.colorAccent), 3, 7);
                        carImageImageView.setImageBitmap(cphDraweBitmap);
                        if(cphYuanBitmap != null && !cphYuanBitmap.isRecycled()){
                            cphYuanBitmap.recycle();
                            cphYuanBitmap = null;
                        }
                    } else {
                        cjhDraweBitmap = ImageUtils.drawTextToRightBottom(CarInfoActivity.this, cjhYuanBitmap, bean.getData().getDate(), locationStr, 32, ContextCompat.getColor(CarInfoActivity.this, R.color.colorAccent), 3, 7);
                        carImageImageView2.setImageBitmap(cjhDraweBitmap);
                        if(cjhYuanBitmap != null && !cjhYuanBitmap.isRecycled()){
                            cjhYuanBitmap.recycle();
                            cjhYuanBitmap = null;
                        }
                    }
                    new pulishImageThread(code == TAKE_CPH_CARMRE_CODE ? cphDraweBitmap : cjhDraweBitmap, bean.getData().getDate() + AppCacheSharedPreferences.getCacheString(Config.PARTNER_ID),
                            bean.getData().getToken(), code).start();
                }
            }
        });
    }

    public class pulishImageThread extends Thread {
        private Bitmap bitmap;
        private String imageName;
        private String token;
        private UploadManager uploadManager;
        private int code;

        public pulishImageThread(Bitmap bitmap, String imageName, String token, int code) {
            this.bitmap = bitmap;
            this.imageName = imageName;
            this.token = token;
            this.code = code;
            uploadManager = new UploadManager();
        }

        @Override
        public void run() {
            super.run();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Message message = handler.obtainMessage();
                    message.what = code == TAKE_CPH_CARMRE_CODE ? PROGRESS_CODE : PROGRESS_VIN_CODE;
                    message.arg1 = 0;
                    handler.sendMessage(message);
                }
            });
            uploadManager.put(ImageUtils.compressImage(bitmap),
                    imageName, token, new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            if (info.isOK()) {
                                try {
                                    if (code == TAKE_CPH_CARMRE_CODE) {
                                        cphPhotoUrl = "http://ozt5bvjey.bkt.clouddn.com/" + response.get("key");
                                    } else {
                                        cjhPhotoUrl = "http://ozt5bvjey.bkt.clouddn.com/" + response.get("key");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                Toast.makeText(CarInfoActivity.this, "图片上传失败,请重新拍照", Toast.LENGTH_SHORT).show();
                            }
                            handler.sendEmptyMessage(code == TAKE_CPH_CARMRE_CODE ? PROGRESS_COMPLETE_CODE : PROGRESS_VIN_COMPLETE_CODE);
                        }
                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                        @Override
                        public void progress(String key, double percent) {
                            Message message = handler.obtainMessage();
                            message.what = code == TAKE_CPH_CARMRE_CODE ? PROGRESS_CODE : PROGRESS_VIN_CODE;
                            message.arg1 = (int) (percent * 100);
                            handler.sendMessage(message);
                        }
                    }, null));

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.unRegisterLocationListener(myListener);
        mLocationClient.stop();
        if (cphYuanBitmap != null && !cphYuanBitmap.isRecycled()) {
            cphYuanBitmap.recycle();
            cphYuanBitmap = null;
        }
        if (cphDraweBitmap != null && !cphDraweBitmap.isRecycled()) {
            cphDraweBitmap.recycle();
            cphDraweBitmap = null;
        }
        if (cjhYuanBitmap != null && !cjhYuanBitmap.isRecycled()) {
            cjhYuanBitmap.recycle();
            cjhYuanBitmap = null;
        }
        if (cjhDraweBitmap != null && !cjhDraweBitmap.isRecycled()) {
            cjhDraweBitmap.recycle();
            cjhDraweBitmap = null;
        }
    }

    public void setCanEdit(boolean flag) {

        //jkr.setEnabled(flag);
        cz.setFocusableInTouchMode(flag);
        cz.setFocusable(flag);

        jkrq.setFocusableInTouchMode(flag);
        jkrq.setFocusable(flag);

        gs.setFocusableInTouchMode(flag);
        gs.setFocusable(flag);

        cx.setFocusableInTouchMode(flag);
        cx.setFocusable(flag);

        cph.setFocusableInTouchMode(flag);
        cph.setFocusable(flag);

        ys.setFocusableInTouchMode(flag);
        ys.setFocusable(flag);

        jkze.setFocusableInTouchMode(flag);
        jkze.setFocusable(flag);

        momo.setFocusableInTouchMode(flag);
        momo.setFocusable(flag);

        cjh.setFocusableInTouchMode(flag);
        cjh.setFocusable(flag);

        jkr.setFocusableInTouchMode(flag);
        jkr.setFocusable(flag);
    }


    public void addCarInfo(String borrower, String carman, String date, String company,
                           String carNo, String carModel, String color, String borrowerAmount, String momo , String vinno) {
        /*HashMap<String , String> hashMap = new HashMap<>();
        hashMap.put("partener" , AppCacheSharedPreferences.getCacheString(Config.PARTNER_ID));
        hashMap.put("account" , "1");
        hashMap.put("borrower" , borrower);
        hashMap.put("carman" , carman);
        hashMap.put("date" , date);
        hashMap.put("company" , company);
        hashMap.put("carNo" , carNo);
        hashMap.put("carModel" , carModel);
        hashMap.put("color" , color);
        hashMap.put("borrowerAmount" , borrowerAmount +"");
        hashMap.put("momo" , "123");
        hashMap.put("state" , 1+"");*/
        /*HashMap<String , String> hashMap = new HashMap<>();
        hashMap.put("partener" , AppCacheSharedPreferences.getCacheString(Config.PARTNER_ID));
        hashMap.put("account" , "1");
        hashMap.put("borrower" , "123");
        hashMap.put("carman" , "123");
       // hashMap.put("date" , "2018-3-8");
        hashMap.put("company" , "123");
        hashMap.put("carNo" , "8888888");
        hashMap.put("carModel" , "458754");
        hashMap.put("color" , "2");
        hashMap.put("borrowerAmount" ,"123");
        hashMap.put("momo" , "123");
        hashMap.put("state" , 1+"");*/
        String url = ApiService.ADD_CAR_INFO_URL + "?" + "location=" + locationStr + "&VINNO=" + vinno + "&date=" + date +"&cjhUrl=" + cjhPhotoUrl +"&cphUrl=" + cphPhotoUrl + "&carId=" + (bean == null ? -1 : bean.getId()) + "&partner=" + AppCacheSharedPreferences.getCacheString(Config.PARTNER_ID) + "&borrower=" + borrower + "&account=" + "1" + "&carman=" + carman + "&company=" + company + "&carNo=" + carNo + "&carModel=" + carModel + "&color=" + color + "&borrowerAmount=" + borrowerAmount + "&momo=" + momo + "&state=0";
        //String url = "http://192.168.1.115:8081/index/addCar?partner=1&borrower=tom&account=1&carman=tom&date=2018-3-8&company=123&carNo=%E6%B5%99C66666&carModel=%E5%8A%B3%E6%96%AF%E8%8E%B1%E6%96%AF&color=%E7%99%BD%E8%89%B2&borrowerAmount=100000&momo=%E5%A5%BD&state=1";
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                is_submit = false;
                Log.d("CarInfoActivity", "失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(CarInfoActivity.this, "您填写的信息有问题.请核实后再保存", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                is_submit = false;
                Log.d("CarInfoActivity", "成功");
                if (response.isSuccessful()) {
                    final BaseBean bean1 = new Gson().fromJson(response.body().string(), BaseBean.class);
                    if (bean1.getCode() == 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(CarInfoActivity.this, bean1.getMsg(), Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(CarInfoActivity.this, bean1.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        });
    }

    public static boolean isValidDate(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
         // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }


}
